package controllers

import (
	"supershare/backend/middleware"
	"supershare/backend/models"

	"github.com/beego/beego/v2/server/web"
	"github.com/beego/beego/v2/server/web/context"
)

// CheckFranchisePermissionResult 权限检查结果
type CheckFranchisePermissionResult struct {
	Admin   *models.Admin // 当前管理员信息
	Success bool          // 是否通过验证
	Code    int           // HTTP状态码
	Message string        // 错误消息
}

// CheckControllerPermission 检查控制器权限
// 返回权限检查结果，包含当前管理员信息和权限状态
func CheckControllerPermission(ctx *context.Context) *CheckFranchisePermissionResult {
	result := &CheckFranchisePermissionResult{
		Success: false,
		Code:    401,
		Message: "未授权访问",
	}

	// 获取当前管理员信息
	admin, err := middleware.GetCurrentAdmin(ctx)
	if err != nil || admin == nil {
		return result
	}

	// 设置管理员信息
	result.Admin = admin
	result.Success = true
	result.Code = 200

	return result
}

// CheckFranchiseResourcePermission 检查加盟商资源权限
// 检查当前管理员是否有权限访问指定加盟商的资源
func CheckFranchiseResourcePermission(admin *models.Admin, resourceFranchiseId int64) *CheckFranchisePermissionResult {
	result := &CheckFranchisePermissionResult{
		Admin:   admin,
		Success: true,
		Code:    200,
	}

	// 验证加盟商权限 - 只有总部管理员或同一加盟商的管理员才能访问
	if admin.FranchiseId > 0 && resourceFranchiseId != admin.FranchiseId {
		result.Success = false
		result.Code = 403
		result.Message = "没有权限访问此数据"
	}

	return result
}

// RespondWithError 响应错误消息
func RespondWithError(controller *web.Controller, result *CheckFranchisePermissionResult) {
	controller.Data["json"] = map[string]interface{}{
		"success": result.Success,
		"message": result.Message,
	}
	controller.ServeJSON()
}
